import axios from 'axios';
import qs from "qs";


export async function getUserList(userAccount, userEmail, userTel, userName, pageNo = 1, pageSize = 10) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params: {
            userAccount,
            userEmail,
            userTel,
            userName,
            pageNo,
            pageSize
        }
    })
    return resp;
}

export async function getRoles(userId) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params: {
            method: 'getRoles',
            userId
        }
    })
    return resp;
}

export async function hasRoles(userId, transferValue) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params:{
            method: 'hasRoles',
            userId,
            roleIds: transferValue
        }
    })
    return resp;
}

export async function deleteUser(userId) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params: {
            method: 'deleteUser',
            userId
        }
    })
    return resp;
}

export async function addUser(ruleForm) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params: {
            method: 'register',
            userAccount: ruleForm.userAccount,
            userPassword: ruleForm.userPassword,
            userTel: ruleForm.userTel,
            userEmail: ruleForm.userEmail,
            userName: ruleForm.userName,
        }
    })
    return resp;
}

export async function updateUser(id, ruleForm) {
    let resp = await axios.get('api/pet_sys/user.do', {
        params: {
            method: 'updateUser',
            userId: id,
            userAccount: ruleForm.userAccount,
            userPassword: ruleForm.userPassword,
            userTel: ruleForm.userTel,
            userEmail: ruleForm.userEmail,
            userName: ruleForm.userName,
        }
    })
    return resp;
}

export async function login(user) {
    var resp = await axios.post(
      "api/pet_sys/user.do",
      qs.stringify({
        method: "login",
        userAccount: user.userAccount,
        userPassword: user.userPassword,
      })
    );
    var token = resp.headers.authorization
    if(token != null || token !== ""){
      localStorage.setItem("token",token);
    }
    if(resp.data.code==0){
      localStorage.setItem("user",JSON.stringify(resp.data.data));
      localStorage.setItem("menuList",JSON.stringify(resp.data.data.menus));
    }
    return resp.data;
  }
  
  export async function verify(){
    var token = localStorage.getItem("token");
    if(token == null){
      return null;
    }
  
    var resp = await axios.get("api/pet_sys/user.do",{
      headers:{
        authorization: `Bearer ${token}`
      },
      params:{
        method:"verify"
      },
    });
    //因为后台返回了一个User对象，这个对象我们在验证成功之后需要赋值给loginUser仓库的
    //data,如果得到值为null，可能仓库在赋值的时候就会报错
    return resp.data
  } 
  
  export function loginOut(){
    localStorage.removeItem("token");
  }

